﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Xml.Linq;
using clf.weighing.entity;
using HandyControl.Controls;
using CheckBox = System.Windows.Controls.CheckBox;
using RadioButton = System.Windows.Controls.RadioButton;

namespace weighing
{
    /// <summary>
    /// 备用字段设置 AddBackupFieldWin.xaml 的交互逻辑
    /// </summary>
    public partial class AddBackupFieldWin : GlowWindow
    {
        #region variabes      
        private readonly string buyName = "BuyWeighingRb";
        private readonly string SaleName = "SaleWeighingRb";
        private readonly string SelfName = "SelfWeighingRb";
        private readonly string foreginName = "ForeginWeighingRb";
        private readonly string mixtureName = "MixtureWeighingRb";
        private readonly string exitSlipName = "ExitSlipRb";
        /// <summary>
        /// 当前 备用字段信息
        /// </summary>
        private BackupBillFieldVo? CurrBackupFieldVo;

        public List<BackupBillField>? BackupFiels;
        #endregion

        #region property
        public WeightingBillType BillType
        {
            get;
            set;
        }

        #endregion

        public AddBackupFieldWin()
        {
            InitializeComponent();
        }

        #region window event

        private void GlowWindow_Loaded(object sender, RoutedEventArgs e)
        {
            this.ContenBorder.DataContext = CurrBackupFieldVo;

            this.CaptureMouse();
        }


        private void GlowWindow_Unloaded(object sender, RoutedEventArgs e)
        {

        }

        private void GlowWindow_ContentRendered(object sender, EventArgs e)
        {
            this.ReleaseMouseCapture();

            CheckedButton();
        }

        private void GlowWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {

        }
        private void GlowWindow_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            if (IsLoaded == false) return;

        }
        private void GlowWindow_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key.Equals(Key.Escape)) this.Close();
        }

        #endregion


        private void Cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox? cb = sender as CheckBox;
            Console.WriteLine(cb?.Name);

            var backupBillField = GetBillField(cb?.Name ?? "");

            backupBillField ??= new BackupBillField()
            {
                id = IdHelper.LongID,
                fiedName = cb?.Name.Replace("CB", ""),
                displayName = cb?.Content?.ToString()?.Replace(" ", ""),
                isEnable = 0,
                isShow = 0,
                isSearch = 0,
                left = 420,
                titleWidth = 60,
                top = 200,
                width = 300,
                sort = 0,
                controlType = (int)BackFieldControlType.TextBox,
                billType = (int)BillType,
            };
            CurrBackupFieldVo = new BackupBillFieldVo(backupBillField);
            this.fieldTb.Text = cb?.Content?.ToString();
            this.fieldNameTb.Text = backupBillField.fiedName;

            SetterCurrFieldValue();
        }


        private void SetterCurrFieldValue()
        {
            if (CurrBackupFieldVo == null)
            {
                this.IsEnableCB.IsChecked = false;
                this.IsShowCB.IsChecked = false;
                this.IsSearchCB.IsChecked = false;
                this.leftTb.Text = String.Empty;
                this.topTb.Text = String.Empty;
                this.widthTb.Text = String.Empty;
                this.displayNameTb.Text = String.Empty;
                this.fieldTb.Text = "未选择备用字段";
                this.fieldNameTb.Text = String.Empty;
                this.titleWidthTb.Text = String.Empty;
                this.textboxRb.IsChecked = false;
                this.comboxRb.IsChecked = false;
                return;
            }

            this.IsEnableCB.IsChecked = CurrBackupFieldVo.IsEnable == 1;
            this.IsShowCB.IsChecked = CurrBackupFieldVo.IsShow == 1;
            this.IsSearchCB.IsChecked = CurrBackupFieldVo.IsSearch == 1;
            this.leftTb.Text = CurrBackupFieldVo.Left.ToString();
            this.topTb.Text = CurrBackupFieldVo.Top.ToString();
            this.widthTb.Text = CurrBackupFieldVo.Width.ToString();
            this.displayNameTb.Text = CurrBackupFieldVo.DisplayName.ToString();
            this.titleWidthTb.Text = CurrBackupFieldVo.TitleWidth.ToString();
            if (CurrBackupFieldVo.ControlType == (int)BackFieldControlType.Combox)
            {
                this.comboxRb.IsChecked = true;
            }
            else
            {
                this.textboxRb.IsChecked = true;
            }
        }

        private void LoadBackUpFields()
        {
            int type = (int)BillType;
            Console.WriteLine("Current bill type:" + type);
            this.BackupFiels = BackupBillFieldDao.Instance.SelectAllByType(type);
        }

        private void ExitSlipRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                LoadBackUpFields();
                UpdateUi(rb.Name);
                var field = GetBillField(rb.Name);
                if (field != null)
                {
                    CurrBackupFieldVo = new BackupBillFieldVo(field);
                }
                else
                {
                    CurrBackupFieldVo = null;
                }

            }
        }

        private void WeighingTypeRb_Checked(object sender, RoutedEventArgs e)
        {
            if (sender is RadioButton rb)
            {
                UpdateUi(rb.Name);
            }
        }

        private void UpdateUi(string rbName)
        {
            if (rbName.Equals(buyName))
            {
                BillType = WeightingBillType.Buy;
            }
            else if (rbName.Equals(SaleName))
            {
                BillType = WeightingBillType.Sale;
            }
            else if (rbName.Equals(SelfName))
            {
                BillType = WeightingBillType.Self;
            }
            else if (rbName.Equals(foreginName))
            {
                BillType = WeightingBillType.Foreign;
            }
            else if (rbName.Equals(exitSlipName))
            {
                BillType = WeightingBillType.ExitSlip;
            }
            else if (rbName.Equals(mixtureName))
            {
                BillType = WeightingBillType.Mixture;
            }
            else
            {
                BillType = WeightingBillType.Otrher;
            }
            //load data 
            LoadBackUpFields();

            CurrBackupFieldVo = null;

            SetterCurrFieldValue();

            CreateBackupRadioButton();

            UpdateBackupRadioButton();
        }

        private void CheckedButton()
        {
            switch (BillType)
            {
                case WeightingBillType.Otrher:
                    break;
                case WeightingBillType.Buy:
                    this.BuyWeighingRb.IsChecked = true;
                    break;
                case WeightingBillType.Sale:
                    this.SaleWeighingRb.IsChecked = true;
                    break;
                case WeightingBillType.Self:
                    this.SelfWeighingRb.IsChecked = true;
                    break;
                case WeightingBillType.Foreign:
                    this.ForeginWeighingRb.IsChecked = true;
                    break;
                case WeightingBillType.Mixture:
                    this.MixtureWeighingRb.IsChecked = true;
                    break;
                case WeightingBillType.UNKNOWN:
                    break;
                case WeightingBillType.ExitSlip:
                    break;
            }
        }

        [Obsolete("Obsolete", true)]
        private void CreateBackupCheckBox()
        {
            this.BackFiledRadioPanel.Children.Clear();
            for (int i = 1; i <= 5; i++)
            {
                CheckBox cb = new CheckBox()
                {
                    Name = $"backup_string{i}CB",
                    Content = $"备用 字符 字段{i}",
                    Margin = new Thickness(4, 2, 4, 2),
                    ToolTip = $"备用 字符 字段{i}",
                    FontSize = 14,
                    Padding = new Thickness(2, 2, 2, 2),
                };
                cb.Checked += Cb_Checked;

                this.BackFiledRadioPanel.Children.Add(cb);
            }
            for (int i = 1; i <= 5; i++)
            {
                var cb = new CheckBox()
                {
                    Name = $"backup_int{i}CB",
                    Content = $"备用 整形 字段{i}",
                    Margin = new Thickness(4, 2, 4, 2),
                    ToolTip = $"备用 整形 字段{i}",
                    Padding = new Thickness(2, 2, 2, 2),
                    FontSize = 14,
                };
                cb.Checked += Cb_Checked;

                this.BackFiledRadioPanel.Children.Add(cb);
            }
            for (int i = 1; i <= 5; i++)
            {
                var cb = new CheckBox()
                {
                    Name = $"backup_decimal{i}CB",
                    Content = $"备用 小数 字段{i}",
                    Margin = new Thickness(4, 2, 4, 2),
                    ToolTip = $"备用 小数 字段{i}",
                    Padding = new Thickness(2, 2, 2, 2),
                    FontSize = 14,
                };
                cb.Checked += Cb_Checked;

                this.BackFiledRadioPanel.Children.Add(cb);
            }
        }

        private void CreateBackupRadioButton()
        {
            this.BackFiledRadioPanel.Children.Clear();
            for (int i = 1; i <= 5; i++)
            {               
                this.BackFiledRadioPanel.Children.Add(GetFieldRB(1,i));
            }
            for (int i = 1; i <= 5; i++)
            {
                this.BackFiledRadioPanel.Children.Add(GetFieldRB(2, i));
            }
            for (int i = 1; i <= 5; i++)
            {
                this.BackFiledRadioPanel.Children.Add(GetFieldRB(3, i));
            }
        }

        private void UpdateBackupRadioButton()
        {
            if (BackupFiels != null)
            {
                foreach (var field in BackupFiels)
                {
                    RadioButton? cb = FindRadioButton(field.fiedName);
                    if (cb != null)
                    {
                        cb.IsChecked = field.isEnable == 1;
                        cb.Content = field.displayName;
                    }
                }
            }
        }

        [Obsolete("",true)]
        private CheckBox? FindCheckBox(string name)
        {
            if (!name.EndsWith("CB")) name += "CB";

            for (int i = 0; i < this.BackFiledRadioPanel.Children.Count; i++)
            {
                var child = this.BackFiledRadioPanel.Children[i] as CheckBox;
                if (child != null)
                {
                    if (child.Name.Equals(name)) return child;
                }
            }
            return null;
        }

        private RadioButton? FindRadioButton(string name)
        {
            if (!name.EndsWith("CB")) name += "CB";

            for (int i = 0; i < this.BackFiledRadioPanel.Children.Count; i++)
            {
                var child = this.BackFiledRadioPanel.Children[i] as RadioButton;
                if (child != null)
                {
                    if (child.Name.Equals(name)) return child;
                }
            }
            return null;
        }

        private BackupBillField? GetBillField(string? name)
        {
            name = name?.Replace("CB", "");
            return BackupFiels?.Find(i => i.fiedName.Equals(name));

        }

        #region save and sned delegete event
        private void SaveBtn_Click(object sender, RoutedEventArgs e)
        {
            if (CurrBackupFieldVo == null) return;

            var field = CurrBackupFieldVo.mBackupBillField;

            var dname = this.displayNameTb.Text;
            if (string.IsNullOrEmpty(dname))
            {
                var msg = "显示名称不能为空";
                this.displayNameTb.Focus();
                Growl.Error(msg);
                return;
            }
            field.fiedName = this.fieldNameTb.Text;
            field.displayName = dname;
            field.isEnable = this.IsEnableCB.IsChecked == true ? 1 : 0;
            field.isShow = this.IsShowCB.IsChecked == true ? 1 : 0;
            field.isSearch = this.IsSearchCB.IsChecked == true ? 1 : 0;
            field.billType = (int)BillType;
            if (this.comboxRb.IsChecked == true)
            {
                field.controlType = (int)BackFieldControlType.Combox;
            }
            else
            {
                field.controlType = (int)BackFieldControlType.TextBox;
            }
            int titelWidth = 60;
            try
            {
                titelWidth = Convert.ToInt32(this.titleWidthTb.Text);
            }
            catch (Exception ex)
            {
                Growl.Error("输入的数值不正确:" + ex.Message);
                this.titleWidthTb.Focus();
                return;
            }
            field.titleWidth = titelWidth;


            int width = 200;
            try
            {
                width = Convert.ToInt32(this.widthTb.Text);
            }
            catch (Exception ex)
            {
                Growl.Error("输入的数值不正确:" + ex.Message);
                this.widthTb.Focus();
                return;
            }
            field.width = width;

            int left = 400;
            try
            {
                left = Convert.ToInt32(this.leftTb.Text);
            }
            catch (Exception ex)
            {
                Growl.Error("输入的数值不正确:" + ex.Message);
                this.leftTb.Focus();
                return;
            }
            field.left = left;

            int top = 200;
            try
            {
                top = Convert.ToInt32(this.topTb.Text);
            }
            catch (Exception ex)
            {
                Growl.Error("输入的数值不正确:" + ex.Message);
                this.topTb.Focus();
                return;
            }
            field.top = top;

            bool isexist = BackupBillFieldDao.Instance.IsExist(field.id);
            int res = 0;
            if (isexist)
            {
                res = BackupBillFieldDao.Instance.Sqlite.Update(field);
            }
            else
            {
                res = BackupBillFieldDao.Instance.Sqlite.Insert(field);
            }

            if (res > 0)
            {
                var m = "保存成功";
                //save success 
                Growl.Clear();
                Growl.Info(m);
                //sned delegete event
                DelegeteFactory.Instance.OnBackupBillFieldChanged?.Invoke(field);

                LoadBackUpFields();

                UpdateBackupRadioButton();
            }
            else
            {
                var m = "保存失败，请重试";
                Growl.Error(m);
            }
        }
        #endregion


        private CheckBox GetFieldCB(int type, int index)
        {
            var text = "";
            var t = "";
            if (type == 1) { text = "字符"; t = "string"; };
            if (type == 2) { text = "整形"; t = "int"; };
            if (type == 3) { text = "小数"; t = "decimal"; };
            CheckBox cb = new CheckBox()
            {
                Name = $"backup_{t}{index}CB",
                Content = $"备用 {text} 字段{index}",
                Margin = new Thickness(10, 2, 4, 2),
                ToolTip = $"备用 {text} 字段{index}",
                Padding = new Thickness(2, 2, 2, 2),
                FontSize = 14,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Left
            };
            cb.Checked += Rb_Checked;

            return cb;
        }

        private RadioButton GetFieldRB(int type, int index)
        {
            var text = "";
            var t = "";
            if (type == 1) { text = "字符"; t = "string"; };
            if (type == 2) { text = "整形"; t = "int"; };
            if (type == 3) { text = "小数"; t = "decimal"; };
            RadioButton rb = new RadioButton()
            {
                Name = $"backup_{t}{index}CB",
                Content = $"备用 {text} 字段{index}",
                Margin = new Thickness(10, 2, 4, 2),
                ToolTip = $"备用 {text} 字段{index}",
                Padding = new Thickness(2, 2, 2, 2),
                FontSize = 14,
                HorizontalAlignment = System.Windows.HorizontalAlignment.Left,
            };
            rb.Checked += Rb_Checked;

            return rb;
        }


        private void Rb_Checked(object sender, RoutedEventArgs e)
        {
            var rb = sender as RadioButton;
            Console.WriteLine(rb?.Name);

            var backupBillField = GetBillField(rb?.Name);

            if (backupBillField == null)
            {
                backupBillField = new BackupBillField()
                {
                    id = IdHelper.LongID,
                    fiedName = rb?.Name.Replace("CB", ""),
                    displayName = rb?.Content?.ToString()?.Replace(" ", ""),
                    isEnable = 0,
                    isShow = 0,
                    isSearch = 0,
                    left = 420,
                    titleWidth = 60,
                    top = 200,
                    width = 300,
                    sort = 0,
                    billType = (int)BillType,
                };
            }
            CurrBackupFieldVo = new BackupBillFieldVo(backupBillField);
            this.fieldTb.Text = rb?.Content.ToString();
            this.fieldNameTb.Text = backupBillField.fiedName;

            SetterCurrFieldValue();
        }


    }
}
